/*
 * @Title Hibernate.java
 * @Description
 * @Copyright Copyright(c) 2018
 * @Company com.lizhen
 * @author lizhen
 * @version 0.0.1
 */
package com.lizhen.core.function.hibernate;

import com.lizhen.core.function.hibernate.entity.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * @author lizhen
 */
public class Hibernate {

    private static final String FILE_PATH = "com\\lizhen\\core\\function\\hibernate\\Hibernate\\hibernate.cfg.xml";
    private static final String ANNOTATION_FILE_PATH = "com\\lizhen\\core\\function\\hibernate\\Hibernate\\hibernate.annotation.cfg.xml";

    /**
     * @author lizhen
     */
    public Hibernate() {
    }

    /**
     * @author lizhen
     */
    public static void main(String[] args) {
        Hibernate hibernate = new Hibernate();
        hibernate.annotation();
        hibernate.xml();
    }

    /**
     * @author lizhen
     */
    private void annotation() {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure(ANNOTATION_FILE_PATH).build();
        SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();
        Person person = new Person();
        person.setName("小明");
        person.setAge(33);
        session.persist(person);
        t.commit();
        session.close();

        System.out.println("successfully saved");
    }

    /**
     * @author lizhen
     */
    private void xml() {
        Configuration cfg = new Configuration();// creating configuration object
        cfg.configure(FILE_PATH);// populates the data of the configuration file
        SessionFactory factory = cfg.buildSessionFactory();// creating seession factory object
        Session session = factory.openSession();// creating session object
        Transaction t = session.beginTransaction();// creating transaction object
        Person person = new Person();
        person.setName("小明");
        person.setAge(55);
        session.persist(person);// persisting the object
        t.commit();// transaction is committed
        session.close();

        System.out.println("successfully saved");
    }
}
